-- 使用hash tag确保相关key在同一个slot
local goodsId = ARGV[1]
local userId = ARGV[2]

-- 使用{}包装goodsId作为hash tag
local stockKey = "seckill:stock:{" .. goodsId .. "}"
local userSetKey = "seckill:success:users:{" .. goodsId .. "}"

local result = {}

local stock = redis.call('DECR', stockKey)
if stock < 0 then
    redis.call('INCR', stockKey)
    result[1] = tostring(-1)
    result[2] = "库存不足"
    result[3] = tostring(stock)
    return result
end

local isMember = redis.call('SISMEMBER', userSetKey, userId)
if isMember == 1 then
    redis.call('INCR', stockKey)
    result[1] = tostring(-2)
    result[2] = "用户已购买"
    result[3] = tostring(stock)
    return result
end

local addResult = redis.call('SADD', userSetKey, userId)
if addResult == 0 then
    redis.call('INCR', stockKey)
    result[1] = tostring(-3)
    result[2] = "系统异常"
    result[3] = tostring(stock)
    return result
end

result[1] = tostring(1)
result[2] = "成功"
result[3] = tostring(stock)
return result